'use strict';
const passwordHash = require('yi-password-hash');
const requireEx = require('yi-require');
const ObjectID = require('mongodb').ObjectID;

const middleware = (req, res, next) => {
    let doc = req.body;
    let authInfo =  req.context||req.context.authInfo ;
    if(!req.context || !req.context.authInfo){
        return res.err.unauthorized();
    }
    authInfo = authInfo.authInfo;

    req.body.userId = ObjectID(authInfo._id);
    req.body.district = doc.province+doc.city+doc.area+doc.detailed;

    let userId = ObjectID(authInfo._id);

    if(doc.defaultBool){
        req.mongo.collection("address").update({userId:userId},{$set:{defaultBool:false}},(e,r)=>{
            if(e) return res.err.mongoError(e);
            next();
        });
    }else{
        doc.defaultBool = false;
        next();
    }
};

module.exports = {
    open : false,
    middleware: middleware,
    description:'添加收货地址',
    handler: requireEx('yi-restful').c('address',[])
};
